package com.py.framework.scheduler.common;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.util.EntityUtils;

import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.http.HttpAsyncAgent;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.log.OutInterfaceLogger;
import com.py.framework.core.log.SystemLogger;

/**
 * 请求任务辅助类
 * @author Leegern
 * @date   2018年5月7日
 */
public class RequestJobHelper {
	
	/** 默认字符集  **/
	public static final String CHARSET_UTF_8 = "utf-8";
	
	/**
	 * 异步任务调度
	 * @param baseUrl 请求的url
	 */
	public static void postAsyncJob(String baseUrl) {
		if (StringUtils.isBlank(baseUrl)) {  
            SystemLogger.info("we don't have base url, check config !");  
            throw new ServiceException("we don't have base url, check config !");  
        }  
        CloseableHttpAsyncClient hc = HttpAsyncAgent.getInstance().getAsyncHttpClient();
        hc.start();  
        HttpPost httpPost = new HttpPost(baseUrl);
        httpPost.setHeader("Connection","close");
        hc.execute(httpPost, new FutureCallback<HttpResponse>() {
        	/*
        	 * (non-Javadoc)
        	 * @see org.apache.http.concurrent.FutureCallback#completed(java.lang.Object)
        	 */
			@Override
			public void completed(HttpResponse result) {
				try {
					String data = EntityUtils.toString(result.getEntity());
					if (StringUtils.isNotBlank(data)) {
						OutInterfaceLogger.info("postAsyncJob success", baseUrl, null, null, null, data);
					}
				} catch (IOException e) {
					ExceptionLogger.error(e);
				}
			}
			/*
			 * (non-Javadoc)
			 * @see org.apache.http.concurrent.FutureCallback#failed(java.lang.Exception)
			 */
			@Override
			public void failed(Exception ex) {
				ExceptionLogger.error("" ,"postAsyncJob error[" + baseUrl + "].", ex);
			}
			/*
			 * (non-Javadoc)
			 * @see org.apache.http.concurrent.FutureCallback#cancelled()
			 */
			@Override
			public void cancelled() {
				
			}
        });  
	}
}